package c;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-27
 * Time: 9:34
 */
public class TcpEchoServer2 {
    ServerSocket serverSocket = null;
    public TcpEchoServer2(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动!");
     //   ExecutorService pool = Executors.newCachedThreadPool();
        ExecutorService pool = Executors.newCachedThreadPool();
        while (true) {

            Socket clientSocket = serverSocket.accept();
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

        }

    }

    public void processConnection(Socket clientSocket) throws IOException {

        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            while (true) {
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()) {
                    System.out.printf("[%s : %d] 客户端下线\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                //读取请求并解析
                String request = scanner.next();
                //根据 请求计算响应
                String response = process(request);
                //将响应写回到客户端
                outputStream.write(response.getBytes());
                System.out.printf("[%s :%d ]  , req= %s ,resp= %s" ,clientSocket.getInetAddress(),clientSocket.getPort(),
                        request,response);


            }
        }finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request+"\n";
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer2 tcpEchoServer = new TcpEchoServer2(9090);
        tcpEchoServer.start();

    }
}
